//
//  NSArray+Util.m
//  wozhua
//
//  Created by 王洋 on 14/10/29.
//  Copyright (c) 2014年 王洋. All rights reserved.
//

#import "NSArray+Util.h"

@implementation NSArray (Util)

- (NSMutableArray *)subarrayAfterCheckWithRange:(NSRange)range {
    NSUInteger checkTotal = range.location + range.length;
    NSMutableArray *subArray;
    if (checkTotal < self.count) {
        subArray = [[NSMutableArray alloc] initWithArray:[self subarrayWithRange:range]];
    } else if (self.count < checkTotal && self.count > range.location) {
        subArray = [[NSMutableArray alloc] initWithArray:[self subarrayWithRange:NSMakeRange(range.location, self.count)]];
    } else {
        subArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return subArray;
}

- (id)objectAtIndexSafe:(NSUInteger)index {
    if (index < self.count) {
        return [self objectAtIndex:index];
    }
    return nil;
}

- (NSDictionary *)dictionaryWithKeyPath:(NSString *)keyPath {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [self enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        id keyValue = [obj valueForKey:keyPath];
        if (keyValue) {
            [dic setObject:obj forKey:keyValue];
        }
    }];
    
    return dic;
}

@end
